<div id="formDiv"></div>
<style>
  #inquiryOrderInformationForm .layui-form-label {
    width: 110px;
  }
  #inquiryOrderInformationForm .layui-input-block {
    margin-left: 130px;
  }
</style>
<script type="text/html" id="formContent">
  <form
    lay-filter="inquiryOrderInformationForm"
    id="inquiryOrderInformationForm"
    class="layui-form open-form"
  >
    <div class="open-model">
      <div class="open-auto">
        <div class="layui-form-item layui-row">
          <input name="id" type="hidden" />
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">客户名称：</label>
            <div class="layui-input-block">
              <select
                id="customerId"
                name="customerId"
                lay-filter="customerId"
                lay-verify="required"
                required
                lay-search=""
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">客户联系人：</label>
            <div class="layui-input-block">
              <select
                id="customerContactsId"
                name="customerContactsId"
                lay-filter="customerContactsId"
                lay-search=""
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">联系人电话：</label>
            <div class="layui-input-block">
              <input
                name="customerContactsPhone"
                id="customerContactsPhone"
                class="layui-input adv-disable"
                disabled
                type="text"
                placeholder="选择联系人自动填充"
                lay-verify="numbers"
              />
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">交货时间：</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input"
                placeholder="交货时间"
                id="deliveryTime"
                lay-verify="required"
                required
                name="deliveryTime"
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item layui-row">
          <!-- <div class="layui-inline layui-col-md3">
                        <label class="layui-form-label">所属渠道：</label>
                        <div class="layui-input-block">
                            <input type="hidden" name="channelId" id="channelId">
                            <input class="layui-input adv-disable" id="channelName"
                                   disabled
                                   placeholder="选择客户自动填充"
                                   name="channelName"
                                   lay-search=""/>
                        </div>
                    </div> -->
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">订单类型：</label>
            <div class="layui-input-block">
              <select
                name="orderType"
                id="orderType"
                class="adv-disable"
                lay-verify="required"
                required
                disabled
              >
                <!--                            <option value="proff">打样订单</option>-->
                <!-- <option value="trial">试产订单</option> -->
                <option value="trial">询价订单</option>
                <option value="mass">量产订单</option>
              </select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <input name="checkerName" type="hidden" />
            <label class="layui-form-label">询价审核人：</label>
            <div class="layui-input-block">
              <select
                id="checkerId"
                name="checkerId"
                lay-verify="required"
                required
                lay-filter="checkerId"
                lay-search=""
              ></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">订单来源：</label>
            <div class="layui-input-block">
              <select name="orderSource" class="adv-disable" disabled>
                <option value="staff">自主录入/员工录入</option>
                <!-- <option value="platform">云端制造/平台指派</option>
                <option value="agent">渠道录入/代理商录入</option>
                <option value="customer">云端智采/客户直接委派</option> -->
              </select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3 isMassOrderBox">
            <label class="layui-form-label">报价截止时间：</label>
            <div class="layui-input-block">
              <input
                type="text"
                class="layui-input"
                id="offerEndTime"
                required
                placeholder="交货时间"
                lay-verify="required"
                name="offerEndTime"
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item layui-row">
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">是否已签约：</label>
            <div class="layui-input-block">
              <select name="hasSign" lay-filter="hasSign">
                <option value="">请选择是否签约</option>
                <option value="1">已签约</option>
                <option value="0">未签约</option>
              </select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3" id="contractIdFormDiv">
            <label class="layui-form-label">选择合同：</label>
            <div class="layui-input-block">
              <select
                name="contractId"
                id="contractId"
                lay-filter="contractId"
              ></select>
            </div>
          </div>
          <!--                <div class="layui-inline layui-col-md3" id="contractIdBox" style="display:none;">-->
          <!--                    <label class="layui-form-label">选择合同</label>-->
          <!--                    <div class="layui-input-inline">-->
          <!--                        <select name="contractId" lay-filter="contractId" lay-verify="required" lay-search=""></select>-->
          <!--                    </div>-->
          <!--                    <div class="layui-word-aux layui-form-mid">-->
          <!--                        <button class="layui-btn layui-btn-xs" id="contractIdAddBtn">添加</button>-->
          <!--                    </div>-->
          <!--                </div>-->
        </div>
        <div class="layui-form-item tableContent">
          <!-- {{# if(['add','edit'].includes(d.eventName)){ }} -->
          <button class="layui-btn" type="button" id="Configure">
            配置物料信息
          </button>
          <!-- {{# } }} -->
          <table
            class="layui-table"
            id="orderFormTable"
            lay-filter="orderFormTable"
          ></table>
        </div>
        <div class="layui-form-item ">
          <label class="layui-form-label w-auto">订单备注说明：</label>
          <div class="layui-input-block" style="margin-left: 130px;">
            <textarea
              placeholder="请输入内容"
              class="layui-textarea"
              style="resize: none"
              name="remark"
            ></textarea>
          </div>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <!-- {{# if(d.eventName == 'zsOrder'){ }} -->
        <button class="layui-btn " type="button" id="zsOrderBtn">
          转正式订单
        </button>
        <!-- {{# } }} -->
        <button
          class="layui-btn layui-btn-primary"
          type="button"
          ew-event="closeDialog"
        >
          关闭
        </button>
        <!-- {{# if(!['acceptance','details'].includes(d.eventName)){ }} -->
        <button
          class="layui-btn"
          lay-filter="inquiryOrderInformationSubmit"
          type="button"
          lay-submit
        >
          提交
        </button>
        <!-- {{# } }} -->
      </div>
    </div>
  </form>
</script>
<script type="text/html" id="orderFormTableBar">
  <!-- {{# if(d.eventName=='acceptance'&&d.statusDesc=='待受理'){ }} -->
  <button class="layui-btn layui-btn-xs" lay-event="accept" type="button">
    受理/评审
  </button>
  <!-- {{# } }} -->
  <!-- {{# if(d.eventName=='acceptance'&&d.statusDesc!='待受理'){ }} -->
  <button class="layui-btn layui-btn-xs" lay-event="acceptDetail" type="button">
    查看详情
  </button>
  <!-- {{# } }} -->
  <!-- {{# if(['edit',undefined].includes(d.eventName)){ }} -->
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del"
    type="button"
  >
    删除
  </button>
  <!-- {{# } }} -->
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };


      let data = nowData?.data;
      // const loadingIndex = layer.load();
      laytpl(formContent.innerHTML).render({ ...nowData }, function (html) { 
        $("#formDiv").after(html);
        $(".isMassOrderBox").toggle(!nowData.isMassOrder);
        $(".isMassOrderBox input").attr("lay-verify", "");
      });

      // add新增 edit修改 detail详情 offer报价 quotationRecord报价记录 acceptance受理/评审
      if (["add", "edit"].includes(nowData.eventName)) {
        admin.setFormDisable(
          "#inquiryOrderInformationForm",
          false,
          ".tableContent"
        );
      } else {
        admin.setFormDisable(
          "#inquiryOrderInformationForm",
          true,
          ".tableContent"
        );
        if (["offer"].includes(nowData.eventName)) {
          $("#inquiryOrderInformationForm")
            .find("button[lay-submit]")
            .toggle(true);
        }
      }

      $("#contractIdFormDiv").hide();
      console.log("data.hasSign", nowData);
      if (data.hasSign && data.hasSign == "1") {
        $("#contractIdFormDiv").show();
      }

      await admin.initDataSelectPro(
        "enterprise/sell/admin/order/getCustomers",
        {},
        "customerId",
        "客户名称",
        async (d) => {
          form.val("inquiryOrderInformationForm", {
            channelName: "",
            customerContactsPhone: "",
            channelId: "",
          });
          const res = await admin.reqPro(
            "enterprise/sell/admin/customersInfo/list",
            { id: d.value },
            "GET"
          );
          $("#channelName").val(res.data[0]?.channelName);
          $("#channelId").val(res.data[0]?.channelId);
          await admin.initDataSelectPro(
            "enterprise/sell/admin/contactInfo/list",
            { selCustomerId: d.value, limit: 9999 },
            "customerContactsId",
            "客户联系人",
            (d, obj) => {
              $("#customerContactsPhone").val(obj?.telephone);
            }
          );
        },
        "customerName"
      );
      if (data.customerId) {
        await admin.initDataSelectPro(
          "enterprise/sell/admin/contactInfo/list",
          { selCustomerId: data.customerId, limit: 9999 },
          "customerContactsId",
          "客户联系人"
        );
        // let list = await admin.reqPro('enterprise/sell/admin/customersInfo/list', {id: data.customerId}, 'GET')
        // $('#channelName').val(list.data[0].channelName)
      }
      await admin.initDataSelectPro(
        "user/admin/user/list",
        { limit: 99999 },
        "checkerId",
        "询价审核人",
        null,
        "nickname,username"
      );
      await admin.initDataSelectPro(
        "enterprise/sell/admin/agentContract/list",
        { status: 1 },
        "contractId",
        "合同"
      );

      laydate.render({
        elem: "#offerEndTime",
        type: "datetime",
        min: new Date().getTime(),
      });
      laydate.render({
        elem: "#deliveryTime",
        type: "datetime",
        min: new Date().getTime(),
      });

      // form.on('select(customerId)',function (data){
      table.render({
        elem: "#orderFormTable",
        // url: config.base + `enterprise/sell/admin/customerProductCatalog/list?limit=9999&customerId=${data.value}`,
        // cellMinWidth: 100,
        page: false,
        limit: 999999,
        data: [],
        cols: [
          [
            { type: "numbers", title: "序号" },
            ,
            {
              field: "skuCode",
              align: "center",
              title: "内部SKU料号",
              width: 120,
              templet: (d) => {
                return d.skuCode ? d.skuCode : "未关联SKU";
              },
            },
            {
              field: "proTypeName",
              align: "center",
              title: "物料类型",
              hide: ["offer"].includes(nowData.eventName),
              width: 120,
            },
            {
              field: "customerSkuItem",
              align: "center",
              title: "客户物料料号",
              width: 120,
            },
            {
              field: "customerSkuName",
              align: "center",
              title: "客户物料名称",
              width: 120,
            },
            {
              field: "customerSpecCode",
              align: "center",
              title: "客户规格码",
              width: 120,
            },
            {
              field: "enclosure",
              align: "center",
              title: "附件",
              hide: ["offer"].includes(nowData.eventName),
              templet: (d) => {
                return d.enclosure
                  ? `<a href="${d.enclosure}" style="color: blue" >下载附件</a>`
                  : "-";
              },
            },
            // , {field: 'skuCode', align: 'center', title: '内部物料料号', width: 120}
            { field: "proUnitName", align: "center", title: "单位", width: 60 },
            {
              field: "quantity",
              align: "center",
              title: "所需数量",
              templet: (d) => {
                return admin.setTableInput(
                  "quantity",
                  !["add", "edit"].includes(nowData.eventName)
                )(d);
              },
            },
            {
              field: "offerMoney",
              align: "center",
              title: "报价",
              templet: (d) => {
                return admin.setTableInput(
                  "offerMoney",
                  !["add", "edit"].includes(nowData.eventName)
                )(d);
              },
              hide: !nowData.isMassOrder,
            },
            {
              field: "remark",
              align: "center",
              title: "备注",
              hide: ["offer"].includes(nowData.eventName),
            },

            {
              field: "hasPack",
              align: "center",
              title: "是否需要包装",
              width: 120,
              hide: ["acceptance", "offer"].includes(nowData.eventName),
              templet: admin.setTableSelect(
                "hasPack",
                [
                  { value: true, label: "是" },
                  {
                    value: false,
                    label: "否",
                  },
                ],
                true
              ),
            },
            {
              field: "packInstructions",
              align: "center",
              title: "包装说明",
              hide: ["acceptance", "offer"].includes(nowData.eventName),
            },
            {
              field: "suggestPrice",
              align: "center",
              title: "最低单价",
              hide: !["offer"].includes(nowData.eventName),
            },
            {
              field: "suggestLowestPrice",
              align: "center",
              title: "建议最低单价",
              hide: !["offer"].includes(nowData.eventName),
            },
            {
              field: "offerMoney",
              align: "center",
              title: "最新报价",
              hide: ["edit", "add", "acceptance"].includes(nowData.eventName),
              templet: admin.setTableInput(
                "offerMoney",
                nowData.eventName != "offer"
              ),
            },
            {
              field: "offerRemark",
              align: "center",
              title: "报价备注",
              hide: !["offer"].includes(nowData.eventName),
              templet: admin.setTableInput("offerRemark", false),
            },
            {
              field: "statusDesc",
              align: "center",
              title: "受理状态",
              hide: ["edit", "add", "offer"].includes(nowData.eventName),
            },
            {
              align: "center",
              toolbar: "#orderFormTableBar",
              title: "操作",
              width: 200,
              hide: ["details", "offer"].includes(nowData.eventName),
            },
          ],
        ],
        done: function (res, curr, count) {
          admin.tableInputChange("orderFormTable");
        },
        error: function () {
          console.log("请求失败");
        },
      });
      if (data.id) {
        data.orderProList?.forEach((v) => (v.eventName = nowData.eventName));
        if (nowData.eventName == "offer") {
          // 如果是报价 筛选出通过受理的列表
          data.orderProList = data.orderProList.filter(
            (v) => v.finalResult == "pass"
          );
        }
        console.log("data", data);
        form.val("inquiryOrderInformationForm", data);
        table.reload("orderFormTable", {
          data: data.orderProList,
        });
        // layer.close(loadingIndex);
      } else {
      }
      // })

      form.on("select(hasSign)", function (data) {
        if (data.value == 1) {
          $("#contractIdFormDiv").show();
          $("#contractId").empty();
          // 选择合同
          admin.initDataSelect(
            "enterprise/sell/admin/agentContract/list",
            { status: 1 },
            "contractId",
            null,
            "合同"
          );
        } else {
          $("#contractId").empty();
          // 选择合同
          admin.initDataSelect(
            "enterprise/sell/admin/agentContract/list",
            { status: 1 },
            "contractId",
            null,
            "合同"
          );
          $("#contractIdFormDiv").hide();
        }
      });
      if(nowData.isMassOrder){
        console.log('nowData',nowData.isMassOrder);
        form.val('inquiryOrderInformationForm',{
          orderType:'mass'
        })
      }
      form.on("submit(inquiryOrderInformationSubmit)", function (d) {
        let formData = { ...d.field };
        formData.customerContactsId = formData.customerContactsId || "0";
        formData.orderProList = table.cache["orderFormTable"];

        console.log("formData", formData);

        // return false;
        if (formData.orderProList.length == 0) {
          layer.msg("请配置物料信息", { icon: 2 });
          return false;
        }
        if (
          formData.orderProList.some(
            (v) =>
              v.quantity == 0 || v.quantity == null || v.quantity == undefined
          )
        ) {
          layer.msg("请填写数量", { icon: 2 });
          return false;
        }
        formData.customerType = "Intended";
        let url = "";
        let method = "";
        if (formData.id) {
          if (nowData.eventName == "edit") {
            url = "enterprise/sell/admin/order/update";
            method = "PUT";
          } else if (nowData.eventName == "offer") {
            formData.orderId = formData.id;
            formData.orderOfferDetailList = table.cache["orderFormTable"].map(
              (v) => {
                return {
                  remark: v.offerRemark,
                  offerMoney: v.offerMoney,
                  proId: v.id,
                  productDetailId: v.productDetailId,
                };
              }
            );
            url = "enterprise/sell/admin/orderOffer/add";
            method = "POST";
          }
        } else {
          url = "enterprise/sell/admin/order/add";
          method = "POST";
        }
        if (nowData.isMassOrder) {
          url = "enterprise/sell/admin/massOrder/addFormalOrder";
          formData.amount = formData.orderProList.reduce(
            (a, b) => a + b.offerMoney * b.quantity,
            0
          );
        }
        admin.req(
          url,
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.closeAll();
              table.reload("orderTable");
              layer.msg("操作成功", { icon: 1 });
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          method,
          true,
          "application/json; charset=utf-8"
        );
        return false;
      });
      // 确保表格的工具栏事件只绑定一次
      // });
      table.on("tool(orderFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["orderFormTable"].filter((v) => {
            return v["LAY_TABLE_INDEX"] != index;
          });
          table.reload("orderFormTable", {
            data: list,
          });
        } else if (layEvent == "accept" || layEvent == "acceptDetail") {
          admin.formOpen({
            area: ["80%", "85%"],
            offset: ["50px", "10%"],
            title: "受理/评审详情",
            path: "components/sell/orderFormAccept.html",
            success: function () {
              parentData.orderObj = d;
              parentData.data = data;
              parentData.eventName = layEvent;
            },
          });
        } else if (layEvent == "quotationRecord") {
        }
      });
      $("#zsOrderBtn").click(function () {
        layer.confirm(
          "确定要转正式订单吗？",
          {
            offset: "65px",
            skin: "layui-layer-admin",
          },
          function (i) {
            admin.req(
              "enterprise/sell/admin/orderOffer/toZSOrder",
              { id: data.id },
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg(res.msg, { icon: 1 });
                  layer.closeAll("page");
                  table.reload("orderTable");
                } else {
                  layer.msg(res.msg, { icon: 2 });
                }
              },
              "POST"
            );
          }
        );
      });
      $("#Configure").click(function () {
        const id = $("#customerId").val();
        if (id) {
          admin.formOpen({
            area: "90%",
            offset: "0px",
            title: "配置订单物料信息",
            path: "components/sell/orderFormTable.html",
            success: function () {
              parentData.id = id;
              parentData.cacheList = [...table.cache["orderFormTable"]];
              if (nowData.isMassOrder) {
                parentData.where = {
                  isHaveInSku: 2,
                };
              }
              // console.log(123,table.cache['orderFormTable'])
            },
            end: function () {
              if (childData.list) {
                const newData = childData.list || [];
                const oldData = table.cache["orderFormTable"];
                const list = [...oldData, ...newData];
                //     newData.map(v => {
                //     const obj = oldData.find(v1 => v1.cusProductId === v.cusProductId);
                //     if (obj) {
                //         return {...obj};
                //     }
                //     return v;
                // })
                table.reload("orderFormTable", {
                  data: list, // 设置新的数据
                });
              }
            },
          });
        } else {
          layer.msg("请选择客户名称");
        }
      });
    }
  );
</script>
<style></style>
